package com.gxuwz.stats.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxuwz.stats.entity.*;
import com.gxuwz.stats.mapper.AcademicWorkMapper;
import com.gxuwz.stats.service.AcademicWorkService;
import com.gxuwz.stats.service.AcademicWorkSumService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@Service
public class AcademicWorkServiceImpl extends ServiceImpl<AcademicWorkMapper, AcademicWork> implements AcademicWorkService {

    @Autowired
    private UserService userService;
    @Autowired
    private AcademicWorkSumService academicWorkSumService;

    /**
     * 用户分页查找
     * @param page
     * @param queryWrapper
     * @return
     */
    @Override
    public IPage<AcademicWork> getAWListWithUserInfo(IPage<AcademicWork> page, QueryWrapper<AcademicWork> queryWrapper) {
        // 查询分页数据
        IPage<AcademicWork> resultPage = this.page(page, queryWrapper);

        // 遍历分页结果，为每个 AcademicWork 对象附加用户信息和关联表信息
        for (AcademicWork academicWork : resultPage.getRecords()) {
            Integer userId = academicWork.getUserId();

            if (userId != null) {
                // 查询用户信息
                User user = userService.getById(userId);

                if (user != null) {
                    academicWork.setUsername(user.getUsername()); // 设置用户名
                }

                // 查询关联表信息（AcademicWorkSum）
                AcademicWorkSum academicWorkSum = academicWorkSumService.getByUserId(userId); // 根据 userId 查询
                System.out.println("academicWorkSum = "+academicWorkSum);
                if (academicWorkSum != null) {
                    academicWork.setAcademicWorkTotalScore(academicWorkSum.getAcademicWorkTotalScore()); // 设置总分值
                    academicWork.setNotes(academicWorkSum.getNotes()); // 设置备注
                } else {
                    // 如果没有对应的记录，设置默认值
                    academicWork.setAcademicWorkTotalScore(0); // 默认总分值为 0
                    academicWork.setNotes(""); // 默认备注为空字符串
                }
            }
        }
//        System.out.println("resultPage77="+resultPage);
        return resultPage;
    }

    @Override
    public void importAcademicWorkData(MultipartFile file) throws IOException {

    }
//    @Autowired
//    private AcademicWorkMapper academicWorkMapper;
//
//    @Autowired
//    private UserService userService; // 获取或插入用户信息
//
//    @Override
//    public void importAcademicWorkData(MultipartFile file) throws IOException {
//        List<Map<Integer, String>> dataList = EasyExcel.read(file.getInputStream())
//                .sheet()
//                .doReadSync();
//
//        if (dataList.isEmpty()) {
//            throw new RuntimeException("Excel 文件为空");
//        }
//
//        Map<Integer, String> headerMap = dataList.get(0); // 第一行是表头
//
//        System.out.println("Header Map: " + headerMap);
//
//        for (int i = 1; i < dataList.size(); i++) {
//            Map<Integer, String> rowData = dataList.get(i);
//
//            String username = rowData.get(getColumnIndex(headerMap, "姓名"));
//            if (username == null || username.trim().isEmpty()) {
//                System.err.println("Skipping invalid record due to missing username.");
//                continue;
//            }
//
//            Integer userId = userService.getUserIdOrInsertUser(username, null, null, null, null);
//
//            // 处理每一行的作品数据
//            parseAndSaveAcademicWork(rowData, headerMap, userId, "作品名称", "出版社名称，出版时间，ISBN号", "类别1", "分值");
//            parseAndSaveAcademicWork(rowData, headerMap, userId, "作品名称", "出版社名称，出版时间，ISBN号", "类别2", "分值");
//            parseAndSaveAcademicWork(rowData, headerMap, userId, "作品名称", "出版社名称，出版时间，ISBN号", "类别3", "分值");
//        }
//    }
//
//    private void parseAndSaveAcademicWork(Map<Integer, String> rowData, Map<Integer, String> headerMap, int userId,
//                                          String workNameKey, String publisherKey, String categoryKey, String scoreKey) {
//        String workName = rowData.get(getColumnIndex(headerMap, workNameKey));
//        if (workName == null || workName.trim().isEmpty()) {
//            return;
//        }
//
////        AcademicWork academicWork = new AcademicWork();
////        academicWork.setUserId(userId);
////        academicWork.setWorkName(workName);
//
//        String publisherInfo = rowData.get(getColumnIndex(headerMap, publisherKey));
//        if (publisherInfo != null && !publisherInfo.trim().isEmpty()) {
//            String[] parts = publisherInfo.split("，");
//            if (parts.length >= 3) {
//                academicWork.setPublisher(parts[0].trim());
//                try {
//                    academicWork.setPublishDate(new SimpleDateFormat("yyyy.MM.dd").parse(parts[1].trim()));
//                } catch (ParseException e) {
//                    System.err.println("日期格式错误：" + parts[1]);
//                }
//                academicWork.setIsbn(parts[2].trim());
//            }
//        }
//
//        academicWork.setAcademicWorkCategory(rowData.get(getColumnIndex(headerMap, categoryKey)));
//        academicWork.setAcademicWorkScore(Integer.parseInt(rowData.getOrDefault(getColumnIndex(headerMap, scoreKey), "0")));
//
//        academicWorkMapper.insert(academicWork);
//    }
//
//    private int getColumnIndex(Map<Integer, String> headerMap, String columnName) {
//        for (Map.Entry<Integer, String> entry : headerMap.entrySet()) {
//            String headerValue = entry.getValue();
//            if (headerValue != null) {
//                // 去除空格并忽略大小写进行比较
//                String normalizedHeaderValue = headerValue.replaceAll("\\s+", "").toLowerCase();
//                String normalizedColumnName = columnName.replaceAll("\\s+", "").toLowerCase();
//                if (normalizedHeaderValue.contains(normalizedColumnName)) {
//                    return entry.getKey();
//                }
//            }
//        }
//        throw new RuntimeException("未找到列名：" + columnName);
//    }

}
